package com.nph.fireworks.client.mvp;

import java.util.Date;

import org.gwttime.time.DateTime;
import org.gwttime.time.Period;
import org.gwttime.time.format.PeriodFormat;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HasWidgets;
import com.nph.fireworks.client.events.StartEvent;
import com.nph.fireworks.client.events.StartEventHandler;

public class CountdownPresenter implements com.nph.fireworks.client.mvp.Presenter {

	private final EventBus eventBus;
	private final CountdownView view;
	private Timer timer;
	private Date endDate;
	
	public interface Display {
		public void setCountdownValue(String v);
		public void update();
	}
	
	public CountdownPresenter(EventBus eventBus, CountdownView view) {
		this.eventBus = eventBus;
		this.view = view;
		
		bind();
	}

	private void bind() {
		timer = new Timer() {

			@Override
			public void run() {
				Date now = new Date();

				if (null == endDate) {
					return;
				}

				DateTime start = new DateTime(now);
				DateTime end = new DateTime(endDate);
				
				Period p = new Period(start, end);
				
//				String s = p.getDays() + " days " + p.getHours() + ":" + p.getMinutes() + ":" + p.getSeconds();
				String s = PeriodFormat.getDefault().print(p);
				
				view.update();
				view.setCountdownValue(s);
			}};
			
		timer.scheduleRepeating(500);
		
		eventBus.addHandler(StartEvent.TYPE, new StartEventHandler(){

			@Override
			public void onStart(StartEvent event) {
				endDate = event.getEndDate();
//				Window.alert("get date! + " + endDate.getTime());
			}});
	}

	public void go(final HasWidgets container) {
		container.clear();
		container.add(view.asWidget());
	}

}
